import { ref, reactive, nextTick } from 'vue'
import { listReport, getReport, delReport, addReport, updateReport } from "@/api/report/report"
import { getDbList, getTableList, getColumnList, validateSql, generateChart } from "@/api/report/report"
import { ElMessage, ElMessageBox } from 'element-plus'

export function useReport() {
  // 基础状态
  const loading = ref(true)
  const ids = ref([])
  const single = ref(true)
  const multiple = ref(true)
  const showSearch = ref(true)
  const total = ref(0)
  const reportList = ref([])
  const title = ref('')
  const open = ref(false)
  const formRef = ref(null)
  const queryFormRef = ref(null)
  const availableColumns = ref([])
  const xColumns = ref([])
  const yColumns = ref([])
  const hasDesc = ref(false)
  const hasTable = ref(false)
  const hasSql = ref(false)
  const hasXy = ref(false)
  const typeOrder = ref({ op: 1, boolean: 2, number: 3, string: 4 })
  const tableViewVisible = ref(false)
  const currentTable = ref({})

  const dbList = ref([])
  const tableList = ref([])
  const tableInfo = ref({})
  const tableColumns = ref({})
  const tableCache = ref({})

  const loadingDb = ref(false)
  const loadingTable = ref(false)

  const chartOption = ref({})
  const chartData = ref([])

  // 查询参数
  const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    reportName: null,
    reportDesc: null,
    genType: null,
    dtInfos: null,
    dtNum: null,
    sqlInfos: null,
    reportX: null,
    reportY: null,
    reportType: null
  })

  // 表单参数
  const form = reactive({
    reportId: null,
    reportName: null,
    reportDesc: null,
    genType: null,
    dtInfos: null,
    dtNum: null,
    sqlInfos: null,
    reportX: null,
    reportY: null,
    showX: null,
    showY: null,
    reportY2: null,
    reportType: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    tableInfos: [],
    xColumns: [],
    yColumns: []
  })

  // 表单校验规则
  const rules = {
    reportName: [{ required: true, message: '报表名称不能为空', trigger: 'blur' }],
    reportDesc: [{ required: true, message: '报表描述不能为空', trigger: 'blur' }],
    genType: [{ required: false, message: '报表生成类型不能为空', trigger: 'change' }],
    dtNum: [{ required: false, message: '库表信息中包含的表的数量不能为空', trigger: 'blur' }]
  }

  const typeChange = {
    'varchar': 'string',
    'int': 'number',
    'double': 'number',
    'decimal': 'number',
    'bigint': 'number',
    'float': 'number',
    'char': 'string',
    'varchar2': 'string',
    'text': 'string',
    'date': 'string',
    'datetime': 'string',
    'timestamp': 'string',
    'boolean': 'boolean',
    'tinyint': 'boolean'
  }

  // 获取列表数据
  const getList = () => {
    loading.value = true
    listReport(queryParams).then(response => {
      console.log('获取报表组件列表成功:', response.rows)
      reportList.value = response.rows
      total.value = response.total
      loading.value = false
    })
  }

  // 表单重置
  const reset = () => {
    form.reportId = null
    form.reportName = null
    form.reportDesc = null
    form.genType = null
    form.dtInfos = null
    form.dtNum = null
    form.sqlInfos = null
    form.reportX = null
    form.reportY = null
    form.reportY2 = null
    form.reportType = 'bar'
    form.createTime = null
    form.updateTime = null
    form.createBy = null
    form.updateBy = null
    form.tableInfos = []
    form.columns = {}
    form.xColumns = []
    form.yColumns = []
  }

  // 搜索按钮操作
  const handleQuery = () => {
    console.log("handleQuery")
    queryParams.pageNum = 1
    getList()
  }

  // 重置按钮操作
  const resetQuery = () => {
    console.log("resetQuery")
    queryFormRef.value?.resetFields()
    handleQuery()
  }

  // 多选框选中数据
  const handleSelectionChange = (selection) => {
    ids.value = selection.map(item => item.reportId)
    single.value = selection.length !== 1
    multiple.value = !selection.length
  }

  // 删除按钮操作
  const handleDelete = (row) => {
    const reportIds = row.reportId || ids.value
    ElMessageBox.confirm('是否确认删除报表编号为"' + reportIds + '"的数据项?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      return delReport(reportIds)
    }).then(() => {
      getList()
      ElMessage.success('删除成功')
    })
  }

  // 导出按钮操作
  const handleExport = () => {
    console.log("handleExport")
    import('@/plugins/download').then(module => {
      module.default.excel(queryParams).then(response => {
        module.default.saveAs(response, `report_${new Date().getTime()}.xlsx`)
      })
    })
  }

  // 新增按钮操作
  const handleAdd = () => {
    console.log("handleAdd")
    reset()
    nextTick(() => {
      xColumns.value = []
      yColumns.value = []
      form.xColumns = []
      form.yColumns = []
      addColumn('x')
      addColumn('y')
    })
    fetchDbList()
    open.value = true
    title.value = "添加报表组件"
  }

  // 修改按钮操作
  const handleUpdate = (row) => {
    console.log("handleUpdate")
    reset()
    const reportId = row.reportId || ids.value
    getReport(reportId).then(response => {
      Object.assign(form, response.data)
      if (form.dtInfos) {
        form.tableInfos = JSON.parse(form.dtInfos)
      }
      if (!form.xColumns?.length) {
        form.xColumns = form.reportX ? JSON.parse(form.reportX): []
        xColumns.value = form.xColumns
        if (form.xColumns.length == 0) {
          addColumn('x')
        }
      }
      if (!form.yColumns?.length) {
        form.yColumns = form.reportY ? JSON.parse(form.reportY): []
        yColumns.value = form.yColumns
        if (form.yColumns.length == 0) {
          addColumn('y')
        }
      }
      fetchDbList()
      open.value = true
      title.value = "修改报表组件"
    })
  }

  // 对话框关闭时的处理
  const handleDialogClosed = () => {
    reset()
    formRef.value?.resetFields()
  }

  // 添加获取数据源列表的方法
  const fetchDbList = async () => {
    loadingDb.value = false
    try {
      const response = await getDbList()
      console.log('获取数据源列表成功:', response.data)
      dbList.value = response.data || []
    } catch (error) {
      console.error('获取数据源列表失败:', error)
      ElMessage.error('获取数据源列表失败')
    } finally {
      loadingDb.value = false
    }
  }

  // 获取表列表
  const fetchTableList = async (dbName) => {
    console.info('获取表列表')
    // 如果缓存中存在，直接返回缓存数据
    if (tableCache.value[dbName]) {
      return tableCache.value[dbName]
    }

    try {
      loadingTable.value = true
      const response = await getTableList(dbName)
      if (!response.data) {
        tableCache.value[dbName] = []
        ElMessage.error('获取表列表失败')
        tableList.value = []
      }
      // tables的格式是[{tableName: 'xxx', tableDesc: 'xxx'}], 需要转为tableName(tableDesc)的格式
      tableList.value = response.data.map(table => table.tableName + '(' + table.tableDesc + ')')
      // 将结果存入缓存
      tableCache.value[dbName] = tableList.value
    } catch (error) {
      console.error('获取表列表失败:', error)
      ElMessage.error('获取表列表失败')
    } finally {
      loadingTable.value = false
    }
  }

  // 处理数据源变化
  const handleDbChange = async (row) => {
    row.table = undefined // 清空表选择
    if (!row.source) return

    // 判断row.source是否在tableCache中
    if (tableCache.value[row.source]) {
      tableList.value = tableCache.value[row.source][0] // 直接赋值
      return
    }

    // 如果不在，调用获取表列表的方法
    tableList.value = await fetchTableList(row.source)

  }

  const handleViewTable = async (index) => {
    console.log('查看表信息', index)
    const row = form.tableInfos[index]
    if (!row.source || !row.table) {
      ElMessage.warning('请先选择数据源和表名')
      return
    }

    try {
      // 设置当前表信息
      currentTable.value = {
        tableName: row.table,
        description: row.description
      }


      // raw.table形式为: tableName(tableDesc),需要提取表名和表描述
      const tableName = row.table.split('(')[0]
      const tableDesc = row.table.split('(')[1]?.slice(0, -1) || ''
      // 获取列信息
      console.log('查询表格信息：', row.source, tableName)
      const response = await getColumnList(row.source, tableName)
      console.log('获取表格信息成功:', response.data)
      const columns = response.data || []
      tableInfo.value = {
        tableName,
        tableDesc,
        columns
      }
      tableColumns.value = {
        tableName: columns
      }

      // 显示弹窗
      tableViewVisible.value = true
    } catch (error) {
      console.error('获取表格信息失败:', error)
      ElMessage.error('获取表格信息失败')
    }
  }

  ///////////////////////////////////////////////
  // 特定接口
  // 在methods部分添加
  const handleAIGenerateTable = () => {
    console.log("handleAIGenerateTable")
    ElMessage.info('正在生成库表信息...')
    // 模拟AI生成库表信息
    setTimeout(() => {
      form.tableInfos = [{
        source: 'wind',
        table: 'stock_types_xxx(股票行情)',
        description: '股票类型数据',
        priority: 'high'
      }]
      hasTable.value = true
      ElMessage.success('库表信息生成成功')
    }, 1000)
  }

  const handleRuleGenerateSQL = async () => {
    console.log("handleRuleGenerateSQL")
    ElMessage.info('正在生成SQL语句...')
    // 基于配置表格form.tableInfos信息，生成SQL语句
    let selectSeg = ''
    let tableSeg = ''
    const alias = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    for (let i = 0; i < form.tableInfos.length; i++) {
      const tableInfo = form.tableInfos[i]
      const tableName = tableInfo.table.split('(')[0]
      console.log('tableName:', tableName, ', tableInfo:', tableInfo)
      const tableAlias = alias[i]
      tableSeg += `${tableInfo.source}.${tableName} ${tableAlias}, `
      if (!tableColumns.value[tableName]) {
        await getColumnList(tableInfo.source, tableName).then(response => {
          tableColumns.value[tableName] = response.data || []
        })
      }
      const columns = tableColumns.value[tableName]
      console.log('tableColumns:', tableColumns)
      console.log('columns:', columns)
      selectSeg += columns.map(col => `${tableAlias}.${col.columnName}`).join(', ') + ', '
    }
    selectSeg = selectSeg.slice(0, selectSeg.length - 2)
    tableSeg = tableSeg.slice(0, tableSeg.length - 2)
    form.sqlInfos = `SELECT ${selectSeg} FROM ${tableSeg} WHERE 1=1`
  }

  const handleAIGenerateSQL = () => {
    console.log("handleAIGenerateSQL")
    ElMessage.info('正在生成SQL语句...')
    // 模拟AI生成SQL
    setTimeout(() => {
      form.sqlInfos = 'SELECT stock_code, stock_name, close_price FROM stock_types_xxx WHERE trade_date = CURRENT_DATE'
      hasSql.value = true
      ElMessage.success('SQL语句生成成功')
    }, 1000)
  }

  const handleSqlInput = (value) => {
    // 在手动写入sql的时候，会自动补全表名和字段名，主要通过"."进行触发，点前面可以是库名，表名，或是表的别名
    // 获取当前光标位置的上下文
    const cursorPosition = value.length;
    const sqlText = value.slice(0, cursorPosition);

    // 检查是否需要触发自动完成
    const match = sqlText.match(/(\w+)\.\s*$/);
    if (match) {
      const prefix = match[1];
      // 判断是数据库还是表
      if (dbList.value.includes(prefix)) {
        // 如果是数据库名，获取该数据库下的表列表
        loadingTable.value = true;
        getTableList(prefix).then(response => {
          console.log('获取表信息成功:', response.data)
          availableColumns.value = response.data.map(table => ({
            value: table.tableName,
            label: table.tableName + '(' + table.tableDesc + ')',
            type: 'table'
          }));
          loadingTable.value = false;
        });
      } else {
        // 如果是表名，获取该表的字段列表
        const currentTable = form.tableInfos.find(t => t.table === prefix);
        if (currentTable) {
          getColumnList(currentTable.source, prefix).then(response => {
            console.log('获取字段信息成功:', response.data)
            availableColumns.value = response.data.map(col => ({
              value: col.columnName,
              label: `${col.columnName} (${col.columnDesc || col.columnType})`,
              type: 'column'
            }));
          });
        }
      }
    }
  }

  // 手动写sql的时候，会下拉提示，然后人工选择
  const handleSelect = (item) => {
    console.log("handleSelect", item)
    // 从item中获取label和value
    const label = item.label
    const value = item.value
    // 从form.sqlInfos中，获取最后一个"."的位置
    const lastCommaIndex = form.sqlInfos.lastIndexOf('.')
    // 将选择的内容的value替换为value
    form.sqlInfos = form.sqlInfos.slice(0, lastCommaIndex + 1) + value
  }

  const handleValidateSQL = () => {
    console.log("handleValidateSQL")
    if (!form.sqlInfos) {
      ElMessage.warning('请先生成SQL语句')
      return
    }
    console.log("form.sqlInfos", form.sqlInfos)
    // 模拟SQL验证
    validateSql({ sql: form.sqlInfos }).then(response => {
      console.log("response", response)
      if (response.code !== 200) {
        ElMessage.error('SQL语句验证失败')
        return
      }
      hasSql.value = true
      ElMessage.success('SQL语句验证成功')
    })
  }

  const handleGetColumns = () => {
    console.log("handleGetColumns")
    if (!form.sqlInfos) {
      ElMessage.warning('请先生成SQL语句')
      return
    }
    console.log("form.sqlInfos", form.sqlInfos)
    let colDict = {}
    form.tableInfos.map(item => {
      if (item.table) {
        const tableName = item.table.split('(')[0]
        console.log("tableName", item.source, tableName)
        console.log("tableColumns", tableColumns.value[tableName])
        tableColumns.value[tableName].map(col => {
          console.log("col", col)
          colDict[col.columnName] = col
        })
      }
    })
    console.log("colDict", colDict)
    // 从sql中，获取select中的字段，作为列名
    const columns = form.sqlInfos.toLowerCase().split('select')[1].split('from')[0].trim().split(',')
    console.log("columns", columns)
    // 如果有使用别名的，只获取别名
    const cs = columns.map(col => {
      const cx = col.trim().split('as')
      const newCol = cx.length > 1 ? cx[1].trim() : cx[0].trim()
      const cx1 = newCol.split('.')

      return cx1.length > 1 ? cx1[1].trim() : cx1[0].trim()
    })
    const css = [...new Set(cs)]
    availableColumns.value = css.map(col => {
      const labelDesc = colDict[col]?.columnDesc || colDict[col]?.columnType || '别名'
      return {
        value: col,
        label: col + ' (' + labelDesc.replace('\n', ' ') + ')',
        type: typeChange[colDict[col]?.columnType] || 'string'
      }
    })
    console.log('获取列信息成功:', availableColumns.value)
  }

  const handleAIGenerateXY = () => {
    console.log("handleAIGenerateXY")
    ElMessage.info('正在生成XY轴配置...')
    // 模拟AI生成XY轴配置
    setTimeout(() => {
      if (form.xColumns.length === 0) addColumn('x')
      if (form.yColumns.length === 0) addColumn('y')

      form.xColumns[0].values = [{ label: '股票代码', value: 'stockCode', type: 'string' }]
      form.yColumns[0].values = [{ label: '收盘价', value: 'closePrice', type: 'number' }]
      form.yColumns[0].aggregation = 'none'

      hasXy.value = true
      ElMessage.success('XY轴配置生成成功')
    }, 1000)
  }

  const handleValidateXY = () => {
    console.log("handleValidateXY")
    // 判断小括号，中括号，大括号是否成对出现
    // 判断数字类型的每一个列中间是否存在op符号，无论是加减乘除还是聚合函数
    // 判断添加聚合函数的列类型是否是number
    // 判断表达试中，有聚合op的列，类型是否是number
    let x = ''
    let y = ''
    const xAliasPrefix = 'tx'
    for (let i = 0; i < xColumns.value.length; i++) {
      const col = xColumns.value[i]
      x += col.values.map(v => {
        return v.type == 'op' || v.type == 'string_op' ? v.value : 'a1.' + v.value
      }).join('') + ','
    }
    const yAliasPrefix = 'ty'
    for (let i = 0; i < yColumns.value.length; i++) {
      const col = yColumns.value[i]
      let yCol = col.values.map(v => {
        return v.type == 'op' || v.type == 'string_op' ? v.value : 'a1.' + v.value
      }).join('')
      if (col.aggregation) {
        yCol = `${col.aggregation}(${yCol})`
      }
      y += yCol + ' as ' + yAliasPrefix + i + ','
    }
    x = x.slice(0, x.length - 1)
    y = y.slice(0, y.length - 1)
    let sqls = form.sqlInfos.split(';')
    const sql = sqls.length > 1 ? sqls[-1] : sqls[0]
    const allSql = `select ${x}, ${y} from (${sql}) a1 group by ${x}`
    console.log("allSql", allSql)
    ElMessage.info('正在验证XY轴配置...')
    // 模拟AI生成XY轴配置
    validateSql({ sql: allSql }).then(response => {
      if (response.code !== 200) {
        ElMessage.error('XY轴配置验证失败')
        return
      }
      console.log("response", response)
      console.log('正在验证XY轴配置:', response.data)
      ElMessage.success('XY轴配置验证成功')
    })
  }

  // 在methods部分添加
  const handleGenerateChart = () => {
    console.log("handleGenerateChart")
    if (!form.reportType) {
      ElMessage.warning('请先选择图表类型')
      return
    }

    let x = ''
    let xg = ''
    let y = ''
    const xAliasPrefix = 'tx'
    for (let i = 0; i < xColumns.value.length; i++) {
      const col = xColumns.value[i]
      let tempx = col.values.map(v => {
        return v.type == 'op' || v.type == 'string_op' ? v.value : 'a1.' + v.value
      }).join('')
      x += tempx + ' as ' + xAliasPrefix + i + ','
      xg += tempx + ','
    }
    const yAliasPrefix = 'ty'
    for (let i = 0; i < yColumns.value.length; i++) {
      const col = yColumns.value[i]
      let yCol = col.values.map(v => {
        return v.type == 'op' || v.type == 'string_op' ? v.value : 'a1.' + v.value
      }).join('')
      if (col.aggregation) {
        yCol = `${col.aggregation}(${yCol})`
      }
      y += yCol + ' as ' + yAliasPrefix + i + ','
    }
    x = x.slice(0, x.length - 1)
    xg = xg.slice(0, xg.length - 1)
    y = y.slice(0, y.length - 1)
    let sqls = form.sqlInfos.split(';')
    const sql = sqls.length > 1 ? sqls[-1] : sqls[0]
    const allSql = `select ${x}, ${y} from (${sql}) a1 group by ${xg}`
    console.log("allSql", allSql)
    ElMessage.info('正在查询数据...')


    generateChart({ sql: allSql }).then(response => {
      if (response.code !== 200) {
        ElMessage.error('查询数据失败')
        return
      }
      console.log('正在查询数据:', response.data)
      ElMessage.success('查询数据成功')
      chartData.value = response.data

      handleReportTypeChange('bar')
    })
  }

  // 提交按钮
  const submitForm = () => {
    console.log("submitForm")
    form.dtInfos = JSON.stringify(form.tableInfos)
    form.dtNum = form.tableInfos.length
    form.reportX = JSON.stringify(form.xColumns)
    form.reportY = JSON.stringify(form.yColumns)
    form.showX = form.xColumns.map(col => col.values.map(v => v.value).join('')).join('<br/>')
    form.showY = form.yColumns.map(col => col.values.map(v => v.value).join('')+';'+col.aggregation).join('<br/>')
    console.log("form:", form)
    form.reportType = form.reportType || 'bar'

    const action = form.reportId != null ? updateReport(form) : addReport(form)
    action.then(() => {
      ElMessage.success(form.reportId != null ? "修改成功" : "新增成功")
      open.value = false
      getList()
    })
  }

  const cancel = () => {
    console.log("cancel")
    open.value = false
    reset()
  }

  ////////////////////////////////////////////////////////
  // 页面交互操作
  // 6. 坐标轴配置相关方法
  // 修改数据结构
  const addColumn = (colType) => {
    console.log("addColumn", colType)
    if (colType === 'x') {
      xColumns.value = [...(xColumns.value || []), { tags: [], type: '', values: [] }]
      form.xColumns = [...xColumns.value]
      console.log("更新后的xColumns的值:", xColumns.value)
    } else {
      yColumns.value = [...(yColumns.value || []), { tags: [], type: '', values: [], aggregation: 'none' }]
      form.yColumns = [...yColumns.value]
      console.log("更新后的yColumns的值:", yColumns.value)
    }

  }

  // 移除XY轴列
  const removeColumn = (colType, index) => {
    console.log("removeColumn", colType)
    if (colType === 'x') {
      xColumns.value = xColumns.value.filter((_, i) => i !== index)
      form.xColumns = [...xColumns.value]
    } else {
      yColumns.value = yColumns.value.filter((_, i) => i !== index)
      form.yColumns = [...yColumns.value]
    }
  }

  // 7. 拖拽相关方法
  // 遍历元素，给每一个元素添加一个index属性, 如果存在，就修改，否则添加
  const updateIndex = (arr) => {
    console.log("updateIndex")
    return arr.map((item, index) => ({ ...item, index }))
  }

  const updateType = (arr) => {
    // 类型op<boolean<number<string
    // 遍历arr元素type, 按照上面的类型级别，级别低的遇到级别高的，就修改
    console.log("updateType")
    let arrType = 0
    for (let i = 0; i < arr.length; i++) {
      const itemType = typeOrder.value[arr[i].type]
      if (itemType > arrType) {
        arrType = itemType
      }
    }
    // 判断typeOrder哪一个value和arrType相等，如果相同，就返回对应的Key
    for (const [key, value] of Object.entries(typeOrder.value)) {
      if (value === arrType) {
        return key
      }
    }
    return 'op'
  }

  const handleTagChange = (colType, columnIndex) => {
    console.log("handleTagChange", colType)
    const column = colType === 'x' ? xColumns.value[columnIndex] : yColumns.value[columnIndex]
    column.type = updateType(column.tags)
    column.values = updateIndex(column.values)
    if (colType === 'x') {
      xColumns.value[columnIndex] = { ...column }
      console.log("xColumns:", xColumns)
      form.xColumns = [...xColumns.value]
    } else {
      yColumns.value[columnIndex] = { ...column }
      console.log("yColumns:", yColumns)
      form.yColumns = [...yColumns.value]
    }
  }

  const handleDrop = (event, colType, columnIndex) => {
    console.log("handleDrop", colType)
    const data = event.dataTransfer.getData('application/x-drag-data')
    const item = JSON.parse(data)

    const column = colType === 'x' ? xColumns.value[columnIndex] : yColumns.value[columnIndex]
    console.log("column", column)

    if (!column.type || column.type === '') {
      column.type = item.type
    } else if (column.type === 'op') {
      column.type = item.type
    } else if (item.type === 'op') {
      // 添加操作符，类型不变
    } else if (column.type !== item.type) {
      // 弹出提示，用户可以确认是否继续
      const old_type = column.type
      ElMessageBox.confirm('该列的类型' + old_type + '与拖拽项的类型' + item.type + '不一致，是否继续？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 用户确认了操作
          if (old_type === 'string' || item.type === 'string') {
            column.type = 'string'
          }
        })
        .catch(() => {
          // 用户取消了操作
          return
        })
    }

    // xColumns.value[columnIndex].tags.push(item.label)
    if (!column.values) {
      column.values = []
    }
    column.values.push(item)
    column.values = updateIndex(column.values)
    if (colType === 'x') {
      xColumns.value[columnIndex] = { ...column }
      console.log("xColumns:", xColumns)
      form.xColumns = [...xColumns.value]
    } else {
      yColumns.value[columnIndex] = { ...column }
      console.log("yColumns:", yColumns)
      form.yColumns = [...yColumns.value]
    }
  }

  // 8. 库表信息相关方法
  const handleAddTable = () => {
    console.log("handleAddTable")
    form.tableInfos.push({
      source: 'wind',
      table: '',
      description: '',
      priority: 'medium'
    });
    hasTable.value = form.tableInfos.length > 0
  }

  const handleDeleteTable = (index) => {
    console.log("handleDeleteTable")
    const newTables = [...form.tableInfos]
    newTables.splice(index, 1)
    form.tableInfos = newTables
  }

  // 图表
  const handleReportTypeChange = (type) => {
    console.log("handleReportTypeChange", type)
    // chartData.value = [{ty0: 5674347, tx0: '其他'}]
    // 基础配置
    const baseOption = {
      title: { text: form.reportName || '数据报表' },
      tooltip: {
        trigger: 'axis',
        formatter: (params) => {
          return params.map(p => `${p.seriesName}: ${p.value}`).join('<br>')
        }
      },
      legend: { data: form.yColumns.map((_, i) => `指标${i + 1}`) },
      toolbox: {
        feature: {
          saveAsImage: {},
          dataZoom: { yAxisIndex: 'none' }
        }
      },
      color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de']
    }

    // const chartOption = ref({
    //   title: {
    //     text: '测试图表'
    //   },
    //   tooltip: {},
    //   xAxis: {
    //     data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
    //   },
    //   yAxis: {},
    //   series: [{
    //     name: '销量',
    //     type: 'bar',
    //     data: [5, 20, 36, 10, 10, 20]
    //   }]
    // })

    switch (type) {
      case 'line':
      case 'bar':
        chartOption.value = {
          ...baseOption,
          title: { text: form.reportName || '数据报表' },
          xAxis: {
            type: 'category',
            // data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
            data: chartData.value.map(item => item.tx0)
          },
          yAxis: {},
          series: form.yColumns.map((col, idx) => ({
            name: `指标${idx + 1}`,
            type: type,
            // data: [5, 20, 36, 10, 10, 20]
            data: chartData.value.map(item => item[`ty${idx}`])
          }))
        }
        break

      case 'pie':
        chartOption.value = {
          ...baseOption,
          series: [{
            type: 'pie',
            radius: '50%',
            data: chartData.value.map(item => ({
              name: item.tx0,
              value: item.ty0
            })),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }]
        }
        break

      case 'scatter':
        chartOption.value = {
          ...baseOption,
          xAxis: { type: 'value' },
          yAxis: { type: 'value' },
          series: [{
            type: 'scatter',
            symbolSize: 20,
            data: chartData.value.map(item => [item.tx0, item.ty0])
          }]
        }
        break
      default:
        chartOption.value = baseOption
    }

    console.log("xAxis:", chartOption.value.xAxis)
    console.log('yAxis:', chartOption.value.yAxis)
    console.log('series', chartOption.value.series)
  }

  return {
    // 属性
    loading,
    ids,
    single,
    multiple,
    showSearch,
    total,
    reportList,
    title,
    open,
    formRef,
    queryFormRef,
    xColumns,
    yColumns,
    hasDesc,
    hasTable,
    hasSql,
    hasXy,
    typeOrder,
    tableViewVisible,
    currentTable,
    tableColumns,
    queryParams,
    form,
    rules,
    dbList,
    tableList,
    tableInfo,
    tableCache,
    loadingDb,
    loadingTable,
    chartOption,
    availableColumns,
    // 方法
    getList,
    reset,
    handleQuery,
    resetQuery,
    handleSelectionChange,
    handleDelete,
    handleExport,
    handleAdd,
    handleUpdate,
    handleDialogClosed,
    fetchTableList,
    handleDbChange,
    handleViewTable,
    handleAIGenerateTable,
    handleRuleGenerateSQL,
    handleAIGenerateSQL,
    handleValidateSQL,
    handleSqlInput,
    handleSelect,
    handleGetColumns,
    handleAIGenerateXY,
    handleValidateXY,
    handleGenerateChart,
    submitForm,
    cancel,
    addColumn,
    removeColumn,
    updateIndex,
    updateType,
    handleTagChange,
    handleDrop,
    handleAddTable,
    handleDeleteTable,
    handleReportTypeChange
  }
}